export default {
    beforeMount(el,binding) {
        let defaultSrc = "";
        //此处可以进行图片的初始化
        LazyLoad.init(el,binding.value,defaultSrc);
    },

    mounted(el) {
        LazyLoad.listenerScroll(el);
    },
}

const LazyLoad:any = {
    init(el:HTMLElement,src:string,drc:string){
        el.setAttribute("data-src",src);
        el.setAttribute("src",drc);
    },
    //监听滚动事件执行加载图片的逻辑，或者借助于浏览器对象加载
    listenerScroll(el:HTMLElement){
        LazyLoad.loadImage(el);

        let handler = LazyLoad.throttle(LazyLoad.loadImage,1000);


        window.addEventListener("scroll",()=>{
            handler(el);
        })
    },

    //开始判断图片加载逻辑对象信息
    loadImage(el:HTMLElement){
        let html = document.documentElement || document.body;

        let {top,bottom} = el.getBoundingClientRect();

        let realSrc = el.getAttribute("data-src");

        if(bottom>0 && top<html.clientHeight){
            //如果有图片的话，直接设置src，删除其他内容
            if(realSrc){
                el.setAttribute("src",realSrc);
                el.removeAttribute("data-src");
            }
        }
    },

    //封装节流的方法，避免请求执行次数过多
    throttle(fn,delay){
        
        let prevTime;
        let context = this;
        return function(...args){
            let currentTime = Date.now();

            if(!prevTime) prevTime = currentTime;

            if(currentTime - prevTime >delay){
                console.log("xxxx");
                //更新过去的时间尺子
                prevTime = currentTime;
                fn.apply(context,args);
                return;
            }
        }
    }
}